window.XMLFormatterRenderer = class XMLFormatterRenderer {
    static getHTML() {
        return `
            <h2 class="text-3xl font-bold text-gray-800 mb-6">XML 格式化工具</h2>
            <p class="text-gray-600 mb-6">格式化、压缩、验证XML文档，支持XML转JSON转换</p>
            
            <!-- 工具栏 -->
            <div class="bg-gray-50 border rounded-lg p-4 mb-6">
                <div class="flex flex-wrap items-center gap-3 mb-4">
                    <button id="format-btn" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="align-left" class="w-4 h-4 mr-2"></i>
                        格式化
                    </button>
                    <button id="minify-btn" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="minimize-2" class="w-4 h-4 mr-2"></i>
                        压缩
                    </button>
                    <button id="validate-btn" class="bg-yellow-600 hover:bg-yellow-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="check-circle" class="w-4 h-4 mr-2"></i>
                        验证
                    </button>
                    <button id="convert-btn" class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="code" class="w-4 h-4 mr-2"></i>
                        转JSON
                    </button>
                    
                    <div class="ml-auto flex items-center space-x-3">
                        <button id="clear-input" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200">
                            清空
                        </button>
                        <button id="load-sample" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200">
                            示例
                        </button>
                        <button id="copy-output" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200">
                            复制
                        </button>
                        <button id="download-output" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200">
                            下载
                        </button>
                    </div>
                </div>
                
                <!-- 格式化选项 -->
                <div class="flex flex-wrap items-center gap-4 text-sm">
                    <div class="flex items-center space-x-2">
                        <label for="indent-size">缩进:</label>
                        <select id="indent-size" class="border rounded px-2 py-1 text-sm">
                            <option value="2" selected>2 空格</option>
                            <option value="4">4 空格</option>
                            <option value="8">8 空格</option>
                        </select>
                    </div>
                    <div class="flex items-center space-x-2">
                        <input type="checkbox" id="remove-comments" class="form-checkbox">
                        <label for="remove-comments">移除注释</label>
                    </div>
                </div>
            </div>

            <!-- 错误提示 -->
            <div id="xml-error" class="hidden bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-4">
                <div class="flex items-center">
                    <i data-feather="alert-circle" class="w-5 h-5 mr-2 text-red-500"></i>
                    <div>
                        <span class="font-medium">XML 格式错误：</span>
                        <span id="xml-error-message"></span>
                    </div>
                </div>
            </div>

            <!-- 成功提示 -->
            <div id="xml-success" class="hidden bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-4">
                <div class="flex items-center">
                    <i data-feather="check-circle" class="w-5 h-5 mr-2 text-green-500"></i>
                    <div>
                        <span class="font-medium">处理成功：</span>
                        <span id="xml-success-message"></span>
                    </div>
                </div>
            </div>

            <!-- 输入区域 -->
            <div class="mb-6">
                <div class="flex items-center justify-between mb-2">
                    <label class="block text-gray-700 text-sm font-bold">
                        输入 XML 数据
                    </label>
                    <div class="text-sm text-gray-500">
                        <span id="xml-input-count">0</span> 字符 | 
                        <span id="xml-input-lines">0</span> 行 |
                        <span id="xml-input-size">0 B</span>
                    </div>
                </div>
                <div class="relative">
                    <textarea id="xml-input" 
                        class="w-full px-4 py-3 text-gray-700 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 code-editor resize-none" 
                        rows="12" 
                        placeholder='请输入或粘贴XML内容...'></textarea>
                </div>
            </div>

            <!-- 输出区域 -->
            <div class="mb-6">
                <div class="flex items-center justify-between mb-2">
                    <label class="block text-gray-700 text-sm font-bold">
                        处理结果
                    </label>
                    <div class="text-sm text-gray-500">
                        <span id="xml-output-count">0</span> 字符 | 
                        <span id="xml-output-lines">0</span> 行 |
                        <span id="xml-output-size">0 B</span> |
                        压缩率: <span id="compression-ratio" class="font-medium text-blue-600">0%</span>
                    </div>
                </div>
                <div class="relative">
                    <div id="xml-output-highlighted" 
                        class="w-full px-4 py-3 text-gray-700 border rounded-lg bg-gray-50 code-editor overflow-auto whitespace-pre-wrap min-h-[300px] max-h-[600px]"
                        style="font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace; font-size: 14px; line-height: 1.5;"
                        ></div>
                    <div class="absolute top-3 right-3 opacity-0 hover:opacity-100 transition-opacity duration-200">
                        <button id="select-all-output" class="bg-gray-500 hover:bg-gray-600 text-white px-3 py-1 rounded text-sm">
                            全选
                        </button>
                    </div>
                </div>
            </div>

            <!-- 统计信息 -->
            <div id="stats-container" class="hidden bg-blue-50 p-4 rounded-lg">
                <h3 class="text-sm font-medium text-gray-700 mb-2">文档统计</h3>
                <div class="grid grid-cols-2 sm:grid-cols-3 gap-4 text-sm">
                    <div>
                        <span class="text-gray-600">元素数量:</span>
                        <span id="stat-elements" class="font-mono ml-1">-</span>
                    </div>
                    <div>
                        <span class="text-gray-600">属性数量:</span>
                        <span id="stat-attributes" class="font-mono ml-1">-</span>
                    </div>
                    <div>
                        <span class="text-gray-600">唯一标签:</span>
                        <span id="stat-unique-tags" class="font-mono ml-1">-</span>
                    </div>
                    <div>
                        <span class="text-gray-600">文本长度:</span>
                        <span id="stat-text-length" class="font-mono ml-1">-</span>
                    </div>
                    <div>
                        <span class="text-gray-600">文件大小:</span>
                        <span id="stat-file-size" class="font-mono ml-1">-</span>
                    </div>
                    <div>
                        <span class="text-gray-600">行数:</span>
                        <span id="stat-lines" class="font-mono ml-1">-</span>
                    </div>
                </div>
            </div>
            
            <!-- 压缩统计 -->
            <div id="compression-stats" class="hidden bg-green-50 p-4 rounded-lg">
                <h3 class="text-sm font-medium text-gray-700 mb-2">压缩统计</h3>
                <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 text-sm">
                    <div>
                        <span class="text-gray-600">原始大小:</span>
                        <span id="stat-original-size" class="font-mono ml-1">-</span>
                    </div>
                    <div>
                        <span class="text-gray-600">压缩后:</span>
                        <span id="stat-compressed-size" class="font-mono ml-1">-</span>
                    </div>
                    <div>
                        <span class="text-gray-600">压缩率:</span>
                        <span id="stat-compression-ratio" class="font-mono ml-1 text-green-600">-</span>
                    </div>
                    <div>
                        <span class="text-gray-600">节省空间:</span>
                        <span id="stat-space-saved" class="font-mono ml-1 text-green-600">-</span>
                    </div>
                </div>
            </div>
        `;
    }
    
    static init() {
        const xmlInput = document.getElementById('xml-input');
        const formatBtn = document.getElementById('format-btn');
        const minifyBtn = document.getElementById('minify-btn');
        const validateBtn = document.getElementById('validate-btn');
        const convertBtn = document.getElementById('convert-btn');
        const clearInputBtn = document.getElementById('clear-input');
        const loadSampleBtn = document.getElementById('load-sample');
        const copyOutputBtn = document.getElementById('copy-output');
        const downloadOutputBtn = document.getElementById('download-output');
        const indentSizeSelect = document.getElementById('indent-size');
        const removeCommentsCheckbox = document.getElementById('remove-comments');
        const selectAllBtn = document.getElementById('select-all-output');
        const errorDiv = document.getElementById('xml-error');
        const successDiv = document.getElementById('xml-success');
        const errorMessage = document.getElementById('xml-error-message');
        const successMessage = document.getElementById('xml-success-message');
        const statsDiv = document.getElementById('stats-container');
        
        let currentMode = 'format';
        let currentResult = null;
        let currentOutput = '';
        
        // 示例XML数据
        const sampleXML = `<?xml version="1.0" encoding="UTF-8"?>
<bookstore xmlns:isbn="http://www.isbn.org">
    <!-- 图书商店库存信息 -->
    <metadata>
        <created>2024-01-15T10:30:00Z</created>
        <lastUpdated>2024-01-15T15:45:30Z</lastUpdated>
        <version>2.1</version>
    </metadata>
    
    <books total="3">
        <book id="1" category="fiction" isbn:number="978-0-7432-7356-5">
            <title lang="en">The Great Gatsby</title>
            <author nationality="American">
                <firstName>F. Scott</firstName>
                <lastName>Fitzgerald</lastName>
            </author>
            <publication>
                <year>1925</year>
                <publisher>Charles Scribner's Sons</publisher>
                <country>USA</country>
            </publication>
            <price currency="USD" discount="10%">12.99</price>
            <description><![CDATA[A classic American novel set in the Jazz Age, exploring themes of decadence and moral decay.]]></description>
            <tags>
                <tag>classic</tag>
                <tag>american literature</tag>
                <tag>20th century</tag>
            </tags>
            <availability inStock="true" quantity="25" />
        </book>
        
        <book id="2" category="science" isbn:number="978-0-553-38016-3">
            <title lang="en">A Brief History of Time</title>
            <author nationality="British">
                <firstName>Stephen</firstName>
                <lastName>Hawking</lastName>
            </author>
            <publication>
                <year>1988</year>
                <publisher>Bantam Doubleday Dell</publisher>
                <country>UK</country>
            </publication>
            <price currency="USD">15.99</price>
            <description>An exploration of cosmology and theoretical physics for general readers.</description>
            <tags>
                <tag>science</tag>
                <tag>physics</tag>
                <tag>cosmology</tag>
            </tags>
            <availability inStock="true" quantity="12" />
        </book>
        
        <book id="3" category="programming" isbn:number="978-0-321-35668-0">
            <title lang="en">Effective Java</title>
            <author nationality="American">
                <firstName>Joshua</firstName>
                <lastName>Bloch</lastName>
            </author>
            <publication>
                <year>2017</year>
                <publisher>Addison-Wesley</publisher>
                <country>USA</country>
                <edition>3rd</edition>
            </publication>
            <price currency="USD">45.99</price>
            <description>Best practices for the Java programming language and platform.</description>
            <tags>
                <tag>programming</tag>
                <tag>java</tag>
                <tag>software development</tag>
            </tags>
            <availability inStock="false" quantity="0" expectedRestock="2024-02-01" />
        </book>
    </books>
</bookstore>`;
        
        // 更新状态显示
        const updateStats = () => {
            const lines = xmlInput.value.split('\n').length;
            const size = new Blob([xmlInput.value]).size;
            
            document.getElementById('xml-input-count').textContent = xmlInput.value.length;
            document.getElementById('xml-input-lines').textContent = lines;
            document.getElementById('xml-input-size').textContent = DevToolsUtils.formatFileSize(size);

            if (currentOutput) {
                const outputLines = currentOutput.split('\n').length;
                const outputSize = new Blob([currentOutput]).size;
                
                document.getElementById('xml-output-count').textContent = currentOutput.length;
                document.getElementById('xml-output-lines').textContent = outputLines;
                document.getElementById('xml-output-size').textContent = DevToolsUtils.formatFileSize(outputSize);
                
                const ratio = xmlInput.value.length > 0 ? 
                    Math.round((1 - currentOutput.length / xmlInput.value.length) * 100) : 0;
                document.getElementById('compression-ratio').textContent = ratio + '%';
            } else {
                document.getElementById('xml-output-count').textContent = '0';
                document.getElementById('xml-output-lines').textContent = '0';
                document.getElementById('xml-output-size').textContent = '0 B';
                document.getElementById('compression-ratio').textContent = '0%';
            }
        };
        
        // 显示成功消息
        const showSuccess = (message) => {
            successMessage.textContent = message;
            successDiv.classList.remove('hidden');
            errorDiv.classList.add('hidden');
            setTimeout(() => {
                successDiv.classList.add('hidden');
            }, 3000);
        };

        // 显示错误消息
        const showError = (message) => {
            errorMessage.textContent = message;
            errorDiv.classList.remove('hidden');
            successDiv.classList.add('hidden');
        };

        // 隐藏所有提示
        const hideMessages = () => {
            errorDiv.classList.add('hidden');
            successDiv.classList.add('hidden');
        };
        
        // 输入事件监听
        xmlInput.addEventListener('input', DevToolsUtils.debounce(() => {
            updateStats();
            
            // 实时验证
            if (xmlInput.value.trim()) {
                const result = XMLFormatter.validateXML(xmlInput.value);
                if (result.success) {
                    DevToolsUtils.removeStatusBorder(xmlInput);
                } else {
                    DevToolsUtils.addErrorBorder(xmlInput);
                }
            } else {
                DevToolsUtils.removeStatusBorder(xmlInput);
            }
        }, 500));
        
        // 格式化XML
        formatBtn.addEventListener('click', () => {
            const xmlContent = xmlInput.value.trim();
            if (!xmlContent) {
                DevToolsUtils.showToast('请输入XML内容', 'warning');
                return;
            }
            
            DevToolsUtils.addLoading(formatBtn);
            hideMessages();

            setTimeout(() => {
                const options = {
                    indent: parseInt(indentSizeSelect.value),
                    removeComments: removeCommentsCheckbox.checked
                };
                
                const result = XMLFormatter.format(xmlContent, options);
                
                if (result.success) {
                    currentOutput = result.data.formatted;
                    document.getElementById('xml-output-highlighted').textContent = currentOutput;
                    
                    currentResult = result.data;
                    currentMode = 'format';
                    this.showStats(result.data.stats);
                    this.hideCompressionStats();
                    DevToolsUtils.showToast('XML格式化成功', 'success');
                    showSuccess(`格式化完成，共 ${currentOutput.split('\n').length} 行`);
                } else {
                    this.displayError(result.error);
                    DevToolsUtils.showToast(result.error, 'error');
                    showError(result.error);
                }
                
                updateStats();
                DevToolsUtils.removeLoading(formatBtn);
            }, 100);
        });
        
        // 压缩XML
        minifyBtn.addEventListener('click', () => {
            const xmlContent = xmlInput.value.trim();
            if (!xmlContent) {
                DevToolsUtils.showToast('请输入XML内容', 'warning');
                return;
            }
            
            DevToolsUtils.addLoading(minifyBtn);
            hideMessages();

            setTimeout(() => {
                const result = XMLFormatter.minify(xmlContent);
                
                if (result.success) {
                    currentOutput = result.data.minified;
                    document.getElementById('xml-output-highlighted').textContent = currentOutput;
                    
                    currentResult = result.data;
                    currentMode = 'minify';
                    this.showCompressionStats(result.data.stats);
                    this.hideStats();
                    DevToolsUtils.showToast('XML压缩成功', 'success');
                    
                    const savedBytes = xmlContent.length - currentOutput.length;
                    const savedPercent = Math.round((savedBytes / xmlContent.length) * 100);
                    showSuccess(`压缩完成，节省了 ${savedBytes} 字符 (${savedPercent}%)`);
                } else {
                    this.displayError(result.error);
                    DevToolsUtils.showToast(result.error, 'error');
                    showError(result.error);
                }
                
                updateStats();
                DevToolsUtils.removeLoading(minifyBtn);
            }, 100);
        });
        
        // 验证XML
        validateBtn.addEventListener('click', () => {
            const xmlContent = xmlInput.value.trim();
            if (!xmlContent) {
                DevToolsUtils.showToast('请输入XML内容', 'warning');
                return;
            }
            
            DevToolsUtils.addLoading(validateBtn);
            hideMessages();

            setTimeout(() => {
                const result = XMLFormatter.validateXML(xmlContent);
                
                if (result.success) {
                    const validationResult = `✅ XML验证通过\n\n根元素: ${result.data.rootElement}\n状态: ${result.data.message}`;
                    currentOutput = validationResult;
                    document.getElementById('xml-output-highlighted').textContent = currentOutput;
                    
                    currentResult = { validated: xmlContent };
                    currentMode = 'validate';
                    this.hideStats();
                    this.hideCompressionStats();
                    DevToolsUtils.showToast('XML验证通过', 'success');
                    showSuccess('XML 格式完全正确！');
                } else {
                    const errorResult = `❌ XML验证失败\n\n错误信息: ${result.error}`;
                    this.displayError(errorResult);
                    DevToolsUtils.showToast('XML验证失败', 'error');
                    showError(result.error);
                }
                
                updateStats();
                DevToolsUtils.removeLoading(validateBtn);
            }, 100);
        });
        
        // XML转JSON
        convertBtn.addEventListener('click', () => {
            const xmlContent = xmlInput.value.trim();
            if (!xmlContent) {
                DevToolsUtils.showToast('请输入XML内容', 'warning');
                return;
            }
            
            DevToolsUtils.addLoading(convertBtn);
            hideMessages();

            setTimeout(() => {
                const result = XMLFormatter.xmlToJson(xmlContent);
                
                if (result.success) {
                    currentOutput = result.data.json;
                    document.getElementById('xml-output-highlighted').textContent = currentOutput;
                    
                    currentResult = result.data;
                    currentMode = 'convert';
                    this.hideStats();
                    this.hideCompressionStats();
                    DevToolsUtils.showToast('XML转JSON成功', 'success');
                    showSuccess('XML转JSON成功');
                } else {
                    this.displayError(result.error);
                    DevToolsUtils.showToast(result.error, 'error');
                    showError(result.error);
                }
                
                updateStats();
                DevToolsUtils.removeLoading(convertBtn);
            }, 100);
        });
        
        // 清空输入
        clearInputBtn.addEventListener('click', () => {
            xmlInput.value = '';
            document.getElementById('xml-output-highlighted').innerHTML = '';
            currentOutput = '';
            this.hideStats();
            this.hideCompressionStats();
            currentResult = null;
            hideMessages();
            statsDiv.classList.add('hidden');
            DevToolsUtils.removeStatusBorder(xmlInput);
            updateStats();
        });
        
        // 加载示例
        loadSampleBtn.addEventListener('click', () => {
            xmlInput.value = sampleXML;
            DevToolsUtils.showToast('已加载示例XML', 'success');
            updateStats();
        });
        
        // 复制输出
        copyOutputBtn.addEventListener('click', async () => {
            if (!currentOutput) {
                DevToolsUtils.showToast('没有可复制的内容', 'warning');
                return;
            }
            
            const success = await DevToolsUtils.copyToClipboard(currentOutput);
            if (success) {
                DevToolsUtils.showToast('已复制到剪贴板', 'success');
            } else {
                DevToolsUtils.showToast('复制失败', 'error');
            }
        });
        
        // 下载输出
        downloadOutputBtn.addEventListener('click', () => {
            if (!currentOutput) {
                DevToolsUtils.showToast('没有可下载的内容', 'warning');
                return;
            }
            
            let filename = 'formatted';
            let mimeType = 'application/xml';
            
            switch (currentMode) {
                case 'format':
                    filename = 'formatted.xml';
                    break;
                case 'minify':
                    filename = 'minified.xml';
                    break;
                case 'convert':
                    filename = 'converted.json';
                    mimeType = 'application/json';
                    break;
                case 'validate':
                    filename = 'validation-result.txt';
                    mimeType = 'text/plain';
                    break;
            }
            
            const blob = new Blob([currentOutput], { type: mimeType });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            DevToolsUtils.showToast('文件已下载', 'success');
        });
        
        // 全选输出按钮
        selectAllBtn.addEventListener('click', () => {
            const outputElement = document.getElementById('xml-output-highlighted');
            const range = document.createRange();
            range.selectNodeContents(outputElement);
            const selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);
            DevToolsUtils.showToast('已全选输出内容！');
        });
        
        // Feather Icons 初始化
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
        
        // 初始化统计信息
        updateStats();
    }
    
    static displayError(errorMessage) {
        const container = document.getElementById('xml-output-highlighted');
        
        const errorHtml = `<div class="text-red-400 p-4">
            <div class="flex items-center mb-2">
                <i class="w-5 h-5 mr-2">⚠️</i>
                <span class="font-bold">错误</span>
            </div>
            <div class="text-red-300">${errorMessage.replace(/\n/g, '<br>')}</div>
        </div>`;
        
        container.innerHTML = errorHtml;
    }
    
    static showStats(stats) {
        const container = document.getElementById('stats-container');
        const elements = document.getElementById('stat-elements');
        const attributes = document.getElementById('stat-attributes');
        const uniqueTags = document.getElementById('stat-unique-tags');
        const textLength = document.getElementById('stat-text-length');
        const fileSize = document.getElementById('stat-file-size');
        const lines = document.getElementById('stat-lines');
        
        elements.textContent = stats.elements;
        attributes.textContent = stats.attributes;
        uniqueTags.textContent = stats.uniqueTags;
        textLength.textContent = stats.textLength;
        fileSize.textContent = DevToolsUtils.formatFileSize(stats.fileSize);
        lines.textContent = stats.lines;
        
        container.classList.remove('hidden');
    }
    
    static hideStats() {
        const container = document.getElementById('stats-container');
        container.classList.add('hidden');
    }
    
    static showCompressionStats(stats) {
        const container = document.getElementById('compression-stats');
        const originalSize = document.getElementById('stat-original-size');
        const compressedSize = document.getElementById('stat-compressed-size');
        const compressionRatio = document.getElementById('stat-compression-ratio');
        const spaceSaved = document.getElementById('stat-space-saved');
        
        originalSize.textContent = DevToolsUtils.formatFileSize(stats.originalSize);
        compressedSize.textContent = DevToolsUtils.formatFileSize(stats.compressedSize);
        compressionRatio.textContent = stats.compressionRatio;
        spaceSaved.textContent = DevToolsUtils.formatFileSize(stats.spaceSaved);
        
        container.classList.remove('hidden');
    }
    
    static hideCompressionStats() {
        const container = document.getElementById('compression-stats');
        container.classList.add('hidden');
    }
};